package org.tgcloud.group.service.task;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.tgcloud.group.core.MapUtil;
import org.tgcloud.group.core.RedisUtil;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.entity.MjNormalUser;
import org.tgcloud.group.entity.MjOtherProject;
import org.tgcloud.group.repository.MjNormalUserMapper;
import org.tgcloud.group.repository.MjOtherProjectMapper;
import org.tgcloud.group.repository.SysLabelValueMapper;
import org.tgcloud.group.service.manager.SysManageService;
import org.tgcloud.group.web.controller.dto.otherProject.OtherProjectChannelUserMsgDTO;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author: zhy
 * @Created: 2024-06-19-下午2:48
 * @Description:
 */
@Component
public class OtherProjectTask {

    private Boolean updateStatus = false;

    @Autowired
    private MjOtherProjectMapper otherProjectMapper;

    @Autowired
    private SysLabelValueMapper sysLabelValueMapper;

    @Autowired
    private MjNormalUserMapper normalUserMapper;

    @Autowired
    private SysManageService sysManageService;

    @Scheduled(cron = "0 * * * * ?")
    public void doUpdateBidding(){
        if (!updateStatus && !RedisUtil.existKey("doCheckOrderTimeOut")){
            RedisUtil.setCacheObject("doUpdateBidding", "doUpdateBidding", 10L, TimeUnit.SECONDS);
            updateStatus = true;
            List<MjOtherProject> list = otherProjectMapper.selectTaskList();
            // 继续参与竞价的界限
            String v4 = sysManageService.doReadOneSysLabelValue(4);
            String v5 = sysManageService.doReadOneSysLabelValue(5);
            // 二次竞价的截止时间
            String v1 = sysManageService.doReadOneSysLabelValue(1);
            for (MjOtherProject otherProject : list){
                BigDecimal topPrice = BigDecimal.ZERO;
                BigDecimal topTwoPrice = BigDecimal.ZERO; // 第一次竞价的第二名价格
                String topFirstKey = null;
                String topTwoKey = null;
                Long topTwoTime = null;
                Integer lastUserId = null;
                Integer oneEndUserNum = 0; // 符合条件的一次竞价结束的渠道用户数量
                boolean isJoinSecond = false; // 是否进入竞价的阶段，true、是，false、否
                if (otherProject.getStatus() == 3){
                    long l = otherProject.getBiddingTwoTimeSlot().multiply(new BigDecimal(3600)).multiply(new BigDecimal(1000)).longValue();
                    Long t = otherProject.getBiddingOneEndTime().getTime() + l;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
                    String nowTime = sdf.format(new Date());
                    String tTime = sdf.format(new Date(t));
                    if (Long.valueOf(nowTime) > Long.valueOf(tTime)){
                        isJoinSecond = true;
                    }
                }else if (otherProject.getStatus() == 2){
                    isJoinSecond = true;
                }
                if (isJoinSecond){
                    List<OtherProjectChannelUserMsgDTO> dtoList = new ArrayList<>();
                    if (StringUtil.isNotBlank(otherProject.getChannelPriceMapJson())){
                        JSONObject channelPriceMapJsonObject = JSONObject.parseObject(otherProject.getChannelPriceMapJson());
                        for (String key : channelPriceMapJsonObject.keySet()){
                            OtherProjectChannelUserMsgDTO dto = channelPriceMapJsonObject.getObject(key, OtherProjectChannelUserMsgDTO.class);
                            if (dto.getStatus() != 94){
                                if (dto.getPrice() == null){
                                    dto.setPrice(BigDecimal.ZERO);
                                }
                                if (dto.getSecondPrice() == null){
                                    dto.setSecondPrice(BigDecimal.ZERO);
                                }
                                if (otherProject.getStatus() == 2){
                                    // 一次竞价
                                    if (dto.getPrice() != null && dto.getPrice().compareTo(topPrice) > 0){
                                        topPrice = dto.getPrice();
                                        topFirstKey = key;
                                    }
                                }else if (otherProject.getStatus() == 3 && isJoinSecond){
                                    // 二次竞价
                                    BigDecimal secondPrice = dto.getSecondPrice();
                                    if (dto.getSecondCommitRecord() == 1 && dto.getRankNum() == 1){
                                        // 处理二次竞价中第一名没有提交表单的情况
                                        secondPrice = dto.getPrice();
                                        dto.setSecondPrice(secondPrice);
                                        dto.setSecondCommitRecord(2);
                                        dto.setSecondTime(dto.getFirstTime());
                                        dto.setIsSecondDiscount(dto.getIsDiscount());
                                    }
                                    if (secondPrice != null && secondPrice.compareTo(topPrice) > 0){
                                        topPrice = secondPrice;
                                        lastUserId = dto.getUserId();
                                    }
                                }
                                dtoList.add(dto);
                                channelPriceMapJsonObject.put(key, dto);
                            }
                        }
                        // 查询出第一次竞价中第二名的价格
                        if (otherProject.getStatus() == 2){
                            for (String key : channelPriceMapJsonObject.keySet()){
                                OtherProjectChannelUserMsgDTO dto = channelPriceMapJsonObject.getObject(key, OtherProjectChannelUserMsgDTO.class);
                                if (dto.getStatus() != 94){
                                    if (dto.getPrice() == null){
                                        dto.setPrice(BigDecimal.ZERO);
                                    }
                                    // 一次竞价
                                    if (dto.getPrice() != null && dto.getPrice().compareTo(topTwoPrice) > 0
                                            && topFirstKey != null && !topFirstKey.equals(key)){
                                        topTwoPrice = dto.getPrice();
                                        topTwoKey = key;
                                        topTwoTime = dto.getFirstTime();
                                    }
                                }
                            }
                        }
                        // 修改渠道状态
                        for (String key : channelPriceMapJsonObject.keySet()){
                            OtherProjectChannelUserMsgDTO dto = channelPriceMapJsonObject.getObject(key, OtherProjectChannelUserMsgDTO.class);
                            if (dto.getStatus() != 94){
                                if (otherProject.getStatus() == 2){
                                    // 一次竞价
                                    //百分比下最低金额
                                    BigDecimal decimal = topPrice.subtract(topPrice.multiply(BigDecimal.valueOf(Long.valueOf(v4))).divide(BigDecimal.valueOf(100L), 2, BigDecimal.ROUND_HALF_UP));
                                    //固定金额下最低金额
                                    BigDecimal subtract = topPrice.subtract(BigDecimal.valueOf(Long.valueOf(v5)));
                                    if (dto.getPrice().compareTo(BigDecimal.ZERO) > 0){
                                        if (decimal.compareTo(dto.getPrice()) > -1){
                                            if (subtract.compareTo(dto.getPrice()) > -1){
                                                dto.setStatus(78);
                                            }else {
                                                dto.setStatus(76);
                                                oneEndUserNum = oneEndUserNum + 1;
                                            }
                                        }else {
                                            dto.setStatus(76);
                                            oneEndUserNum = oneEndUserNum + 1;
                                        }
                                    }else {
                                        dto.setStatus(78);
                                    }
                                    // 第一次竞价出现第二名并且第二名是竞价失败的时候，把第二名改成竞价成功
                                    if (dto.getStatus() == 78 && topTwoPrice.compareTo(BigDecimal.ZERO) > 0){
                                        if (topTwoKey != null && topTwoKey.equals(key)){
                                            oneEndUserNum = oneEndUserNum + 1;
                                            dto.setStatus(76);
                                        }
                                    }
                                }else if (otherProject.getStatus() == 3 && isJoinSecond){
                                    if (dto.getStatus() != 78){
                                        // 二次竞价
                                        if (dto.getUserId() == lastUserId){
                                            dto.setStatus(93);
                                        }else {
                                            dto.setStatus(92);
                                        }
                                    }
                                }
                                channelPriceMapJsonObject.put(key, dto);
                            }
                        }
                        if (otherProject.getStatus() == 2 && oneEndUserNum == 1){
                            for (String key : channelPriceMapJsonObject.keySet()){
                                OtherProjectChannelUserMsgDTO dto = channelPriceMapJsonObject.getObject(key, OtherProjectChannelUserMsgDTO.class);
                                if (dto.getStatus() == 76){
                                    lastUserId = dto.getUserId();
                                }
                            }
                        }
                        // 判断lastUserId，如果有值，那么获取lastUserId的开拓者
                        Integer pushLastUserId = null;
                        if (lastUserId != null){
                            MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(lastUserId);
                            pushLastUserId = mjNormalUser.getPushUserId();
                        }
                        JSONObject userStatusMapJson = JSONObject.parseObject(otherProject.getUserStatusMapJson());
                        if (otherProject.getStatus() == 2){
                            // 一次竞价
                            otherProject.setStatus((short) 3);
                            otherProject.setBiddingTwoTimeSlot(new BigDecimal(v1));
                            otherProject.setBiddingOneFirstPrice(topPrice);
                            for (String userKey : userStatusMapJson.keySet()){
                                userStatusMapJson.put(userKey, 87);
                            }
                            if (oneEndUserNum <= 1){
                                otherProject.setStatus((short) 4);
                                if (oneEndUserNum == 1){
                                    otherProject.setLastUserId(lastUserId);
                                    for (String key : channelPriceMapJsonObject.keySet()){
                                        OtherProjectChannelUserMsgDTO dto = channelPriceMapJsonObject.getObject(key, OtherProjectChannelUserMsgDTO.class);
                                        if (dto.getUserId() == lastUserId){
                                            dto.setStatus(93);
                                        }else {
                                            dto.setStatus(92);
                                        }
                                    }
                                }
                                for (String userKey : userStatusMapJson.keySet()){
                                    userStatusMapJson.put(userKey, 88);
                                    if (userKey.equals("user_" + pushLastUserId)){
                                        userStatusMapJson.put(userKey, 99);
                                    }
                                }
                            }
                            // 使用Stream API进行排序
                            List<OtherProjectChannelUserMsgDTO> sortedTransactions = dtoList.stream()
                                    // 先按Price降序
                                    .sorted(Comparator.comparing(OtherProjectChannelUserMsgDTO::getPrice, Comparator.reverseOrder())
                                            // 然后在Price相同的情况下按FirstTime升序
                                            .thenComparing(OtherProjectChannelUserMsgDTO::getFirstTime))
                                    .collect(Collectors.toList());
                            // 赋值-rankNum
                            for(String userKey : channelPriceMapJsonObject.keySet()){
                                OtherProjectChannelUserMsgDTO channelUserMsgDTO = channelPriceMapJsonObject.getObject(userKey, OtherProjectChannelUserMsgDTO.class);
                                for (int i = 0; i < sortedTransactions.size(); i++){
                                    OtherProjectChannelUserMsgDTO dto = sortedTransactions.get(i);
                                    if (channelUserMsgDTO.getUserId().equals(dto.getUserId())){
                                        channelUserMsgDTO.setRankNum(i + 1);
                                        channelPriceMapJsonObject.put(userKey, channelUserMsgDTO);
                                    }
                                }
                            }
                        }else if (otherProject.getStatus() == 3 && isJoinSecond){
                            // 二次竞价
                            otherProject.setStatus((short) 4);
                            otherProject.setLastUserId(lastUserId);
                            otherProject.setBiddingTwoTopPrice(topPrice);
                            for (String userKey : userStatusMapJson.keySet()){
                                userStatusMapJson.put(userKey, 88);
                                if (userKey.equals("user_" + pushLastUserId)){
                                    userStatusMapJson.put(userKey, 99);
                                }
                            }
                            // 使用Stream API进行排序
                            List<OtherProjectChannelUserMsgDTO> sortedTransactions = dtoList.stream()
                                    // 先按Price降序
                                    .sorted(Comparator.comparing(OtherProjectChannelUserMsgDTO::getSecondPrice, Comparator.reverseOrder())
                                            // 然后在Price相同的情况下按FirstTime升序
                                            .thenComparing(OtherProjectChannelUserMsgDTO::getSecondTime))
                                    .collect(Collectors.toList());
                            // 赋值-rankNum
                            for(String userKey : channelPriceMapJsonObject.keySet()){
                                OtherProjectChannelUserMsgDTO channelUserMsgDTO = channelPriceMapJsonObject.getObject(userKey, OtherProjectChannelUserMsgDTO.class);
                                for (int i = 0; i < sortedTransactions.size(); i++){
                                    OtherProjectChannelUserMsgDTO dto = sortedTransactions.get(i);
                                    if (channelUserMsgDTO.getUserId().equals(dto.getUserId())){
                                        channelUserMsgDTO.setSecondRankNum(i + 1);
                                        channelPriceMapJsonObject.put(userKey, channelUserMsgDTO);
                                    }
                                }
                            }
                        }
                        otherProject.setChannelPriceMapJson(JSONObject.toJSONString(channelPriceMapJsonObject));
                        otherProject.setUserStatusMapJson(JSONObject.toJSONString(userStatusMapJson));
                        otherProjectMapper.updateByPrimaryKeySelective(otherProject);
                    }
                }
            }
            updateStatus = false;
        }
    }

}
